<template>
  <div class="p-2">
    <div class="goods_form">
      <!-- 顶部步骤条 star -->
<!--      <div class="step_bar">-->
<!--        <div class="step">-->
<!--          <div :class="{item:true,check:query.step == 1,success:query.step>1}">-->
<!--            <el-icon :size="16">-->
<!--              <List />-->
<!--            </el-icon>-->
<!--            编辑商品-->
<!--          </div>-->
<!--          <div :class="{item:true,check:query.step == 3,success:query.step>3}">-->
<!--            <el-icon :size="16">-->
<!--              <SetUp />-->
<!--            </el-icon>-->
<!--            规格编辑-->
<!--          </div>-->
<!--          <div class="item">-->
<!--            <el-icon :size="16">-->
<!--              <CircleCheckFilled />-->
<!--            </el-icon>-->
<!--            发布商品-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
      <!-- 顶部步骤条 end -->
      <!-- 商品主体 star -->
      <div class="goods_form_item" v-if="query.step == 1">
        <el-form ref="formRef" label-position="right" :model="form" :rules="rules" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="当前类目" prop="cate3Id">
                <el-cascader
                  style="width: 300px;"
                  v-model="form.cate3Id"
                  :options="categoryList"
                  :props="{ children: 'children', label: 'name', value: 'id' }"
                  @change="handleChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品品牌" prop="brandId">
                <el-select v-model="form.brandId" placeholder="请选择品牌id" clearable :disabled="query.isDisabled"
                           style="width: 100%">
                  <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品标题" prop="name">
                <el-input v-model="form.name" placeholder="请输入商品标题" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="副标题" prop="subName">
                <el-input v-model="form.subName" type="textarea" :rows="2" placeholder="请输入副标题" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="商品图片" prop="imgUrl">
                <image-upload v-model="form.ossId" @update:urls="url" class="custom-upload" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item :label="'平台价格'" prop="price">
                <el-input type="number" v-model="form.price">
                  <template #suffix>￥</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="'市场价格'" prop="oldPrice">
                <el-input type="number" v-model="form.oldPrice">
                  <template #suffix>￥</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item :label="'商品库存'" prop="goods_stock">
                <el-input type="number" v-model="form.stock" :suffix-icon="PieChart" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品详情" prop="details">
                <editor v-model="form.details.content" :min-height="200" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="'是否上架'" prop="status">
                <el-switch v-model="form.status" :active-value="1" :inactive-value="0" @change="statusChange" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
<!--                <el-button type="primary" @click="nextStep(3)" :disabled="disabled">下一步，填写规格信息</el-button>-->
                <el-button type="primary" @click="handleAdd" :disabled="disabled">下一步，填写规格信息</el-button>
                <el-button :icon="CircleCheck" type="success" :loading="loading" @click="nextStep(2)">发布</el-button>
                <el-button @click="goodsBack">返回</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--商品主体 end-->

      <div class="goods_form_item" v-if="query.step == 2">
        <el-result icon="success" title="操作成功" sub-title="等待页面跳转……" />
      </div>
<!--------------------------------------------商品规格 star------------------------------------------>
      <div class="goods_form_item" v-if="query.step == 3">
        <div class="spec">
          <el-form>
            <el-button class="btn" type="primary" @click="addSpec"> 添加规格</el-button>
            <el-text class="spec-checkbox" v-for="item in skuData.goodsAttr" :key="item.id">
              <template #default>
                <span class="text" style="margin-bottom: 15px;">{{ item.name }}</span>
                <el-icon class="delete" @click="deleteSpec(item)">
                  <Delete />
                </el-icon>
                <div class="spec-value">
                  <div v-for="vo in item.specValues" :key="vo.id || 'empty-' + index">
                    <el-checkbox class="value-checkbox" @change="specChange(item,vo)" :value="vo.check||false"
                                 :checked="vo.check||false">{{ vo.name }}
                    </el-checkbox>
                    <el-icon v-if="!vo.check" class="delete" @click="deleteValue(vo, index)">
                      <Delete />
                    </el-icon>
                  </div>
                  <el-button type="primary" class="value-btn" link icon="Plus" @click="addSpecValue(item)">新增规格项
                  </el-button>
                </div>
              </template>
            </el-text>
          </el-form>

        </div>
        <!--sku-->
        <div class="sku">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="SKU信息" prop="goodsSkus">
                <el-table :data="skuData.skus" border>
                  <el-table-column v-slot="scope" label="规格名称" width="200">
                    <input v-model="scope.row.skuName" class="custom-input" />

                  </el-table-column>
                  <el-table-column label="图片" v-slot="scope" width="60" align="center">
                    <el-upload
                      class="avatar-uploader"
                      :action="uploadImgUrl"
                      :show-file-list="false"
                      :on-success="
                    (response: any, uploadFile: any, fileList: any) =>
                      handleSkuSuccess(
                        response,
                        uploadFile,
                        fileList,
                        scope.row
                      )
                  "
                      :headers="headers"
                    >
                      <img
                        v-if="scope.row.imgUrl"
                        :src="scope.row.imgUrl"
                        class="avatar"
                        alt=""
                      />
                      <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>
                  </el-table-column>
                  <el-table-column v-slot="scope" label="商品价格" width="160">
                    <input v-model="scope.row.price" class="custom-input" />
                  </el-table-column>
                  <el-table-column v-slot="scope" label="市场价" width="160">
                    <input v-model="scope.row.oldPrice" class="custom-input" />
                  </el-table-column>
                  <el-table-column v-slot="scope" label="库存数量" width="200">
                    <input v-model="scope.row.stock" class="custom-input" />
                  </el-table-column>
                  <el-table-column v-slot="scope" label="商家编码">
                    <input v-model="scope.row.skuCode" class="custom-input" />
                  </el-table-column>
                  <el-table-column v-slot="scope" label="商品条形码">
                    <input v-model="scope.row.barCode" class="custom-input" />
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-form>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item class="btn-bottom">
                  <el-button :icon="CircleCheck" type="success" :loading="loading" @click="handleGoods">发布</el-button>
                  <el-button @click="cancel">返回</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

        </div>
        <!-- 规格名称弹窗 -->
        <el-dialog v-model="dialogVisible" title="添加规格" width="500px">
          <el-form :model="specForm">
            <el-form-item label="商品ID" label-width="80px">
              <el-input v-model="specForm.goodsId" disabled></el-input>
            </el-form-item>
            <el-form-item label="规格名称" label-width="80px">
              <el-input v-model="specForm.name" placeholder="输入规格名称"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">返回</el-button>
                    <el-button type="primary" @click="handleSpec">添加</el-button>
                </span>
          </template>
        </el-dialog>
        <!--规格值弹窗-->
        <el-dialog v-model="dialogValue" title="添加规格" width="500px">
          <el-form :model="specValueForm">
            <el-form-item label="规格ID" label-width="80px">
              <el-input v-model="specValueForm.specId" disabled></el-input>
            </el-form-item>
            <el-form-item label="属性名称" label-width="80px">
              <el-input v-model="specValueForm.name" placeholder="输入规格值名称"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogValue = false">返回</el-button>
                    <el-button type="primary" @click="handleSpecValue">添加</el-button>
                </span>
          </template>
        </el-dialog>

      </div>

      <!--商品规格 end -->
    </div>
  </div>
</template>
<script setup lang="ts">

import { CircleCheck, CircleCheckFilled, Delete, List, PieChart, Plus, Reading, SetUp } from '@element-plus/icons-vue';
import { MallGoodsForm, MallGoodsQuery } from '@/api/mall/mallGoods/types';
import { listGoodsCategory } from '@/api/mall/goodsCategory';
import { listCateBrand } from '@/api/mall/cateBrand';
import { addGoodsSpec, delGoodsSpec, specByGoodsIdListApi } from '@/api/mall/goodsSpec';
import SkuItem from '@/views/mall/mallGoods/components/SkuItem.vue';
import { addMallGoods, delGoodsSkuApi, updateMallGoods } from '@/api/mall/mallGoods';
import { globalHeaders } from '@/utils/request';
import { addGoodsSpecVal, delGoodsSpecVal } from '@/api/mall/goodsSpecVal';
const props = defineProps({
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emit = defineEmits(['closeAdd','getList'])
const loading = ref(false);
const formRef = ref<ElFormInstance>();
const disabled = ref(false);
// const dialogVisible = ref(false)
const specs = ref([])
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + '/resource/oss/upload'); // 上传的图片服务器地址
const headers = ref(globalHeaders());
const specForm = ref({//商品规格
  name: '',
  goodsId: ''
});
const specValueForm = ref({//商品规格值
  name: '',
  specId: ''
});
const skuData = reactive({//sku表
  goodsAttr: [],
  skus: []
});
const query = reactive({
  step: 1,
  choseId: [0, 0, 0],
  index: [0, 0, 0],
  classList: [],
  choseItem: [{}, {}, {}],
  isDisabled: true
});

const initFormData: MallGoodsForm = {
  id: undefined,
  brandId: undefined,
  cate1Id: undefined,
  cate2Id: undefined,
  cate3Id: undefined,
  name: undefined,
  subName: undefined,
  price: undefined,
  oldPrice: undefined,
  imgUrl: undefined,
  ossId: undefined,
  sale: undefined,
  collect: undefined,
  status: 0,
  verify: undefined,
  refuseInfo: undefined,
  freightId: undefined,
  contentMobile: undefined,
  isRecommend: undefined,
  isMaster: undefined,
  specs: [],
  skus: [{}],
  details: {}
};
const data = reactive<PageData<MallGoodsForm, MallGoodsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {},
    cateId: undefined,
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    cate3Id: [{ required: true, message: '商品分类不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '销售量不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '上架状态不能为空', trigger: 'change' }],
    details: [{ required: true, message: '详情不能为空', trigger: 'change' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
watch(
  () => props.rowData,
  () => {
    console.log(props.rowData);
    form.value = props.rowData as any;
    queryParams.value.cateId = props.rowData.cateId;
    // 品牌可编辑
    // isDisabled.value = false;
    // 参数
    queryParams.value.cateId = props.rowData.cate3Id;
    //复选框选中状态
    // selectedSpecIds.value = form.value.specValue.map((item) => item.specId);
    //添加商品规格所需的goods_id
    // specForm.value.goodsId = props.rowData.id;
    skuData.skus = props.rowData.skus

  }
);
watch(()=>query.step,()=>{
  if(query.step ===2){
//关闭添加，回到列表页
    setTimeout(()=>{
      emit('closeAdd',1)
    },500)
    emit('getList')
  }
})
/*获取分类列表*/
type GoodsCategoryOption = {
  id: number;
  name: string;
  children?: GoodsCategoryOption[];
};
const categoryList = ref<GoodsCategoryOption[]>([]);
const getCategoryData = async () => {
  let res = await listGoodsCategory();
  console.log(res);
  categoryList.value = res.data;
};

/*选择分类后获取对应值*/
const specCateId = ref<number>(null);
const handleChange = (value) => {
  //商品分类第3级
  queryParams.value.cateId = value[2];
  //商品规格参数
  specCateId.value = value[2];
  //商品分类赋值
  form.value.cate1Id = value[0];
  form.value.cate2Id = value[1];
  form.value.cate3Id = value[2];
  //查询商品品牌
  query.isDisabled = false;
  getBrandData();
};
/*获取品牌列表*/
const brandList = ref<any>([]);
const getBrandData = async () => {
  const { rows } = await listCateBrand(queryParams.value);
  console.log(rows);
  brandList.value = rows;
};
/*图片组件回传值*/
const url = (e: []) => {
  form.value.imgUrl = e.join(',');
};

/*添加商品规格界面*/
const addSpec = ()=>{
  dialogVisible.value = true;
  specForm.value.goodsId = props.rowData.id;

}
// 公共返回列表页面
const goodsBack = () => {
  location.reload();
};

/*商品上架*/
const statusChange = (ev) => {
  form.value.status = ev;
};
/*下一步，商品发布*/
const handleAdd=()=>{
  //仅在非编辑状态下执行
  formRef.value.validate(async (valid)=>{
    if(!valid) return false;
    if(form.value.id){
      const res = await updateMallGoods(form.value)
      console.log(res);
      specQueryParams.value.goodsId = res.data
      //执行获取spec列表的方法
      await getSpecs()
    }else{
      //TODO 对比数据有变化才执行编辑动作
      const res = await addMallGoods(form.value)
      console.log(res);
      //TODO 页面跳转，带上res.data传过去
      specQueryParams.value.goodsId = res.data
      // specForm.value.goodsId = res.data
      await getSpecs()
    }
    //页面跳转
    query.step = 3
  })
}
/*获取商品规格*/
const specQueryParams =ref({
  goodsId: ""
})
const nextStep = (e) => {
  query.step = e;
  if (e === 2) { //发布
    formRef.value.validate(async (valid)=>{
      //这里结果是false怎么仍然执行了下一下步呢
      if(!valid) return false;
        if(form.value.id){
          await updateMallGoods(form.value)
        }else{
          await addMallGoods(form.value)
        }
      //关闭添加，回到列表页
      setTimeout(()=>{
        emit('closeAdd',1)
      },500)
      emit('getList')
    })
  }
  if (query.step === 1) { //添加商品
    // getSpecs();
    formRef.value?.validate((valid) => {
      console.log(valid);
      if (valid) {
        disabled.value = true
      }
    });
  }
  if (query.step === 3) { //添加sku
    getSpecs();
  }
}
/*======================================规格属性操作 start ===========================================*/

const dialogVisible = ref(false);
const dialogValue = ref(false);
//sku图片
const handleSkuSuccess = (
  response: any,
  uploadFile: any,
  fileList: any,
  row: any
) => {
  row.imgUrl = response.data.url;
};

/*获取规格列表*/
const getSpecs = async () => {
  console.log(specQueryParams.value.goodsId);
  const res = await specByGoodsIdListApi(specQueryParams.value);
  skuData.goodsAttr = res.data;
  console.log(res);
};

/*返回或取消*/
const cancel = () => {
  query.step = 1
};

/*添加商品规格操作*/
const handleSpec = async () => {
  const res = await addGoodsSpec(specForm.value);
  if (res.code === 200) {
    await getSpecs();//刷新spec列表
    dialogVisible.value = false; //关闭弹窗
    //重置输入框
    specForm.value.name = '';
  }
};
/*删除商品规格*/
const deleteSpec = async (ev) => {
  const { code } = await delGoodsSpec(ev.id);
  if (code === 200) {
    //刷新规格列表
    await getSpecs();
  }
};
/*添加商品规格值界面*/
const addSpecValue = (ev) => {
  dialogValue.value = true;
  specValueForm.value.specId = ev.id;
};
/*添加商品规格值操作*/
const handleSpecValue = async () => {
  const { code } = await addGoodsSpecVal(specValueForm.value);
  if (code === 200) {
    //重置输入框
    specValueForm.value.name = '';
    //关闭弹窗
    dialogValue.value = false;
    //刷新商品规格
    await getSpecs();
  }
};

/*删除框*/
const deleteValue = (item) => {
  //先执行后台删除
  delGoodsSpecVal(item.id)
    .then((res) => {
      //删除前端数据
      if (res.code === 200) {
        //删除对应的sku
      }
      //刷新specValue列表
      getSpecs();
    })
    .catch((error) => {
      ElMessage.error('删除失败', error);
    });
};

/*=======属性选择 start =========================*/
const specChange = (attrs, specs) => {
  console.log("a是",attrs,);
  console.log("b是",specs,);
  let index = -1;
  skuData.goodsAttr.forEach((items, key) => {
    if (items.id === attrs.id) {
      index = key;
    }
  });

  if (index !== -1) {
    skuData.goodsAttr[index].specValues.forEach((item) => {
      if (item.id === specs.id) {
        item.check = item.check === undefined ? true : !item.check;
      }
    });
  }

  structureSku();
};

const structureSku = () => {
  let skuList = [];
  let attrList = [];
  let attrListName = [];
  let i = 0;

  skuData.goodsAttr.forEach((items) => {
    let checkedValues = [];
    items.specValues.forEach(specItem => {
      if (specItem.check) {
        checkedValues.push(specItem.id);
        if (attrList[i] === undefined) {
          attrList[i] = [];
          attrListName[i] = [];
        }
        attrList[i].push(specItem.id);
        attrListName[i].push(specItem.name);
      }
    });
    if (checkedValues.length > 0) {
      i++;
    }
  });

  if (attrList.length === 0) {
    skuData.skus = [];
    //如果清空，则对当前的skus进行删除
    delSkus(props.goods.id);
    return;
  }
  // 处理单选情况
  if (attrList.every(arr => arr.length === 1)) {
    // 直接为每个选中的规格值生成 SKU
    attrList.forEach((ids, index) => {
      const skuAttributes = [{
        name: skuData.goodsAttr[index].name,
        valueName: attrListName[index][0]
      }];

      skuList.push({
        specId: ids,
        skuName: attrListName[index][0],
        oldPrice: 0,
        price: 0,
        stock: 0,
        attributes: skuAttributes
      });
    });
  } else {
    // 处理多选情况
    const attrName = cartesianProduct(attrListName);
    const attrId = cartesianProduct(attrList);

    attrId.forEach((ids, key) => {
      let skuAttributes = [];
      for (let j = 0; j < ids.length && j < skuData.goodsAttr.length; j++) {
        if (attrList[j] && attrList[j].length > 0) {
          const index = attrList[j].indexOf(ids[j]);
          if (index !== -1) {
            skuAttributes.push({
              name: skuData.goodsAttr[j].name,
              valueName: attrListName[j][index]
            });
          }
        }
      }

      skuList.push({
        specId: ids,
        skuName: attrName[key].join('+'),
        oldPrice: 0,
        price: 0,
        stock: 0,
        attributes: skuAttributes
      });
    });
  }
  // 更新SKU列表
  if (skuData.skus && skuData.skus.length > 0) {
    const newSkuIds = skuList.map(sku => JSON.stringify(sku.specId.sort((a, b) => a - b)));
    const oldSkuIds = skuData.skus.map(sku => JSON.stringify(sku.specId.sort((a, b) => a - b)));

    // 移除不再存在的SKU
    skuData.skus = skuData.skus.filter((sku, index) => newSkuIds.includes(oldSkuIds[index]));

    // 添加新的SKU
    skuList.forEach(newSku => {
      if (!oldSkuIds.includes(JSON.stringify(newSku.specId.sort((a, b) => a - b)))) {
        skuData.skus.push(newSku);
      }
    });
  } else {
    skuData.skus = skuList;
  }
};

const cartesianProduct = (array) => {
  if (array.length == 1) {
    return array;
  }
  return array.reduce(function(a, b) {
    return a.map(function(x) {
      return b.map(function(y) {
        return x.concat(y);
      });
    }).reduce(function(a, b) {
      return a.concat(b);
    }, []);
  }, [[]]);
};

/*=========属性选择 end ============*/

/*商品发布*/
const handleGoods = async () => {
  // 将 data.skus 中的每个对象的 specId 和 attributes 转换为 JSON 字符串
  skuData.skus = skuData.skus.map((obj) => {
    // 创建一个新对象，并更新 specId 和 attributes 为 JSON 字符串
    return {
      ...obj,
      specId: JSON.stringify(obj.specId),
      attributes: JSON.stringify(obj.attributes)
    };
  });
  console.log(skuData.skus);
  // 将转换后的数组赋值给 props.goods.skus
  // const { code } = await updateMallGoods(props.goods);
  const { code } = await updateMallGoods(formRef.value);
  if (code === 200) {
    //关闭当前页
    emit('step', 2);
  }
};
const delSkus = async (goodsId) => {
  try {
    const { code } = await delGoodsSkuApi(goodsId);
    if (code === 200) {
      ElMessage.success('原有sku商品已被全部删除');
    }
  } catch (error) {
    ElMessage.error(error);
  }
};
/*======================================规格属性操作 end ===========================================*/
onMounted(() => {

  getCategoryData();
});

</script>
<style scoped lang="scss">
.goods_form{
  padding: 20px 60px;
}
.step {
  height: 46px;
  line-height: 46px;
  background: #F5F7FA;
  margin-bottom: 50px;
  display: flex;

  .item {
    flex: 1;
    font-size: 16px;
    color: #C0C4CC;
    text-align: center;
    border-right: 4px solid #fff;
    justify-content: center;
    align-items: center;
    display: flex;

    i {
      margin-right: 10px;
    }

    &.check {
      color: #333;
      font-weight: bold;
    }

    &.success {
      color: #67C23A;
      font-weight: bold;
    }

    &:last-child {
      margin-right: 0px;
    }
  }
}
.spec {
  display: block;
  flex-direction: column;

  .btn {
    margin: 10px;
  }

  .spec-checkbox {
    display: block;
    flex-direction: column;
    background: #F7F8FA;
    margin-bottom: 10px;
    padding: 30px 20px;
    border-radius: 10px;

    .text {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .spec-value {
      margin-top: 10px;
      display: flex;

      .value-checkbox {
        padding-left: 20px;
      }

      .value-btn {
        margin-left: 15px;
      }
    }
  }
}

.delete {
  margin-left: 5px;
  margin-right: 20px;
  cursor: pointer;
  color: #FF6600;
}

.sku {
  margin-top: 10px;
}

.custom-input {
  width: 100%;
  height: 30px;
  border: none;

  &:focus {
    outline: none;
  }
}

.empty-placeholder {
  font-size: 12px;
  color: #c03639;
}

.avatar-uploader .avatar {
  width: 30px;
  height: 30px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 26px;
  color: #8c939d;
  width: 30px;
  height: 30px;
  text-align: center;
}

.btn-bottom {
  margin-top: 20px;
}
</style>
